package com.es.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.util.StringUtils;


@Configuration
public class EsConfig extends AbstractElasticsearchConfiguration {

    @Value("${elasticsearch.username}")
    private String username;
    @Value("${elasticsearch.password}")
    private String password;
    @Value("${elasticsearch.urls}")
    private String urls;

    @Override
    public RestHighLevelClient elasticsearchClient() {
        if (StringUtils.isEmpty(urls)) {
            throw new RuntimeException("elasticsearch.urls为空");
        }
        String[] temp = urls.split(",");
        HttpHost[] httpHostArr = new HttpHost[temp.length];
        for (int i = 0; i < temp.length; i++) {
            String urlStr = temp[i];
            if (StringUtils.isEmpty(urlStr)) {
                continue;
            }
            httpHostArr[i] = HttpHost.create(urlStr);
        }

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        return new RestHighLevelClient(
            RestClient.builder(httpHostArr).setHttpClientConfigCallback(httpClientBuilder -> {
                httpClientBuilder.disableAuthCaching();
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }));
    }

}
